package storage

import (
	"fmt"
	"github.com/pkg/sftp"
	"golang.org/x/crypto/ssh"
	"io"
	"log"
)

func NewSFTP(address, username, password string) *SFTP {
	config := &ssh.ClientConfig{
		User:            username,
		Auth:            []ssh.AuthMethod{ssh.Password(password)},
		HostKeyCallback: ssh.InsecureIgnoreHostKey(),
	}
	conn, err := ssh.Dial("tcp", address, config)
	if err != nil {
		log.Fatalf("创建SFTP客户端失败： %v", err)
	}

	client, err := sftp.NewClient(conn)
	if err != nil {
		log.Fatalf("创建SFTP客户端失败： %v", err)
	}

	return &SFTP{client: client}
}

type SFTP struct {
	client *sftp.Client
}

func (s *SFTP) Upload(bucketName, objectName string, reader io.Reader) error {
	w, err := s.client.Create(objectName)
	if err != nil {
		return fmt.Errorf("上传文件失败： %v", err)
	}
	defer w.Close()

	_, err = io.Copy(w, reader)
	if err != nil {
		return fmt.Errorf("上传文件失败： %v", err)
	}
	return nil
}

func (s *SFTP) Download(bucketName, objectName string, writer io.Writer) error {
	r, err := s.client.Open(objectName)
	if err != nil {
		return fmt.Errorf("下载文件失败： %v", err)
	}
	defer r.Close()

	_, err = io.Copy(writer, r)
	if err != nil {
		return fmt.Errorf("写入文件失败： %v", err)
	}
	return nil
}
